package com.home.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.home.biz.PhoneBiz;
import com.home.config.InitDataConfig;
import com.home.entity.CoinResult;
import java.util.concurrent.Callable;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ：chenxf
 * @date ：Created in 2020/8/3 10:12
 * @description：
 * @modified By：
 * @version: $
 */
@Slf4j
public class FetchCoinUtil implements Callable<String> {
    static String url="https://api.bqex.org/polarisex/order/order?buyOrSell=1&baseCurrencyId=4&currencyId=173&fdPassword=&num=#NUM&price=#PRICE&source=1&type=1&uuid=7c92d42e874c42ce8edeae19f2c0b269&uid=2240394&token=#TOKEN&local=";
    static String refer="http://www.bqb.pub/exchange";

    static String resultUrl="https://api.bqex.org/polarisex/user/showOrderList?baseCurrencyId=4&currencyId=173&start=1&size=20&uuid=7c92d42e874c42ce8edeae19f2c0b269&uid=2240394&token=#TOKEN&local=";
    static String priceUrl="https://api.bqex.org/polarisex/quote/klineHistory?type=10&symbol=USDT_MNW&limit=1&uuid=7c92d42e874c42ce8edeae19f2c0b269&uid=2240394&token=#TOKEN&local=";
    static String tokenUrl="https://api.bqex.org/polarisex/user/signin?diallingcode=86&phone=18322392919&password=582f0b53c73d587f4b078b4c6dfadf74&validate=6kGGmT2ANbFHk9mi5wyy8Dg1bRrFRK8knO8qOCIIjYb7J1DbVYp.FPF-X_jvngLnmBFF71AWWfpezH_uq8dlDeBITPhd7b66cUHweyDeZQ0ZnE-AZrW7LBXOzCyVx0mQSHSF8rGbkfiCKLYC9bi8_PPlZzwU0tY_QBuoD4bMAf9FK4MFvr00A_yaH5.TpLxw6dHrsV0t7L8V1Pb1l7lZHLKNf2HnmcfEpDJ4oZeN25SK_SGbZ8Mh5Oho0F_YKdb2Z61cZBEDvZu7pKiu.hk5vZ5RLUqVYBEn-GpnAMff4t98oU00qlWmP60qwdk00JE57ZXzu-sElizI6sDAedQ1a4cD-NdOU5GH8BYcmuhf0S5DzCLsfNDzuCs00XY_alnzccY.eoqGwcZoLjIO4GfcehiaAc.HVEm4qK77oycEo1g9eIOUMSmjDCoYD.5Yf1fOTsC4Xi55nrMJPmz9rkRZhCIXd45fKJ6PriMh9CtlX7b7wxbchOap7qG2rRF3&source=1&local=";
    String token="",price="",num="num";
    int times=0;

    public FetchCoinUtil(String token){
        this.token=token;
    }
    public FetchCoinUtil(String token,String num,String price){
        this.token=token;
        this.price=price;
        this.num=num;
    }
    @Override
    public String call() throws Exception {
        fetch();
        return "fetch finish";
    }

    public String price() throws Exception {
        String doc = Jsoup.connect(priceUrl.replace("#TOKEN",token))
                //.requestBody(data)
                .ignoreContentType(true)
                .method(Connection.Method.GET)
                .header("Content-Type","application/json")
                .header("Connection","keep-alive")
                .header("Referer",refer)
                .userAgent("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)")
                .execute()
                .body();
        JSONObject map= JSON.parseObject(doc);
        if("200".equals(map.get("status").toString())){
            log.debug("fetch price finished");
            String curPrice=map.getJSONArray("attachment").getJSONObject(0).getString("current");
            if (!curPrice.equals(InitDataConfig.getPrice())) {
                InitDataConfig.setPrice(curPrice);
                //多线程下单
                buy(curPrice);
            }
            return curPrice;

        }else {
            log.error("采集异常");
        }
        return null;
    }

    public void buy(String price) throws Exception{
        ExecutorService executorService= Executors.newFixedThreadPool(5);
        int num=InitDataConfig.getNum();
        for(int i=0;i<num;i++){
           executorService.submit(new FetchCoinUtil(InitDataConfig.getToken(),InitDataConfig.getVeryCode(), price));

        }

    }

    public List<CoinResult> orders(boolean isSuccess) throws Exception {
        String doc = Jsoup.connect(resultUrl.replace("#TOKEN",token))
                //.requestBody(data)
                .ignoreContentType(true)
                .method(Connection.Method.GET)
                .header("Content-Type","application/json")
                .header("Referer",refer)
                .userAgent("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)")
                .execute()
                .body();
        JSONObject map= JSON.parseObject(doc);
        if("200".equals(map.get("status").toString())){
            log.debug("fetch order finished");
            JSONObject obj=map.getJSONObject("attachment");

            List<CoinResult> results;
            if(isSuccess){
                //成功
                results=JSON.parseArray(obj.getJSONArray("tradeSuccess").toJSONString(),CoinResult.class);
                results.stream().forEach(e->{e.updateStatus();e.setStatus("已完成");});
            }else {
                results=JSON.parseArray(obj.getJSONArray("tradeFail").toJSONString(),CoinResult.class);
                results.stream().forEach(e->{e.updateStatus();e.setStatus("未完成");});
            }
            return results;
        }else if("9999".equals(map.get("status").toString())){
            times++;

            if(times<2){
                token();
                return orders(isSuccess);
            }

        }else {
            log.error("采集异常");
        }
        return new ArrayList<CoinResult>();
    }

    public boolean token() throws Exception {
        String doc = Jsoup.connect(tokenUrl)
                //.requestBody(data)
                .ignoreContentType(true)
                .method(Connection.Method.POST)
                .header("Content-Type","application/json")
                .header("Referer",refer)
                .userAgent("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)")
                .execute()
                .body();
        JSONObject map= JSON.parseObject(doc);
        if("200".equals(map.get("status").toString())){
            this.token=map.getJSONObject("attachment").getString("token");
            InitDataConfig.setToken(token);
            return true;
        }
        return false;
    }

    public boolean fetch() throws Exception {
       // log.debug("buy data"+token);
        String doc = Jsoup.connect(url.replace("#TOKEN",token).replace("#NUM",num).replace("#PRICE",price))
                //.requestBody(data)
                .ignoreContentType(true)
                .method(Connection.Method.POST)
                .header("Content-Type","application/json")
                .header("Referer",refer)
                .userAgent("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)")
                .execute()
                .body();
       // log.debug("buy data={}",doc);
        JSONObject map= JSON.parseObject(doc);
        if("200".equals(map.get("status").toString())){
            InitDataConfig.setNum((InitDataConfig.getNum() - 1));
           log.debug("buy finished");
            return true;
        }else if("9999".equals(map.get("status").toString())){
            times++;

            if(times<2){
                token();
                return fetch();
            }
        }else {
          //  log.error("采集异常");
        }
        return false;
    }




}
